#!/usr/bin/env bash


function get_select_option() {
  local _line OLD_IFS _opt
  _line=$(echo "$*" | sed '/^$/d' | wc -l)
  if [[ $_line -eq 1 ]]; then
    echo "$*"
  elif [[ $_line -gt 1 ]]; then
    OLD_IFS=${IFS}
    OLD_PS3=${PS3}
    IFS=$'\n'
    PS3="choose an option: "
    select _opt in $(echo "$*"); do
      if [[ -n $_opt ]]; then
        echo $_opt
        break
      else
        echo 'out of range'
      fi
    done
    IFS=${OLD_IFS}
    PS3=${OLD_PS3}
  else
    echo 'optoins is none'
    return 1
  fi
}
function multi_select() {
  local _line OLD_IFS options num choices prompt msg
  options=($*)
  _line=$(echo "$*" | sed '/^$/d' | wc -l)
  if [[ $_line -eq 1 ]]; then
    echo "$*"
  elif [[ $_line -gt 1 ]]; then
    OLD_IFS=${IFS}
    IFS=$'\n'
    echo "Avaliable options:" >&2
    function __show_menu() {
      for i in "${!options[@]}"; do
        printf "%3d%s) %s\n" $((i+1)) "${choices[i]:-}" "${options[i]}" >&2
      done
      if [[ -n $msg ]]; then
        echo "$msg" >&2
      fi
    }
    prompt="check an option (again to uncheck, ENTER when done): "
    while __show_menu && read -rp "$prompt" num && [[ "$num" ]]; do
      [[ -z $num ]] && { continue; }
      [[ "$num" != *[![:digit:]]* ]] &&
      (( num > 0 && num <= ${#options[@]} )) ||
      { msg="Invalid option: $num"; continue; }
      ((num--)); msg="${options[num]} was ${choices[num]:+un}checked"
      [[ "${choices[num]}" ]] && choices[num]="" || choices[num]="+"
    done
    for i in ${!options[@]}; do
      [[ "${choices[i]}" ]] && { printf "%s\n" "${options[i]}"; }
    done
    IFS=${OLD_IFS}
  else
    echo 'optoins is none' >&2
    return 1
  fi
}
function single_select() {
  local _line OLD_IFS options num choices prompt msg
  options=($*)
  _line=$(echo "$*" | sed '/^$/d' | wc -l)
  if [[ $_line -eq 1 ]]; then
    echo "$*"
  elif [[ $_line -gt 1 ]]; then
    OLD_IFS=${IFS}
    IFS=$'\n'
    echo "Avaliable options:" >&2
    function __show_menu() {
      for i in "${!options[@]}"; do
        printf "%3d%s) %s\n" $((i+1)) "${choices[i]:-}" "${options[i]}" >&2
      done
      if [[ -n $msg ]]; then
        echo "$msg" >&2
      fi
    }
    prompt="check an option (again to uncheck, ENTER when done): "
    while __show_menu && read -rp "$prompt" num; do
      [[ -z $num ]] && { continue; }
      [[ "$num" != *[![:digit:]]* ]] &&
      (( num > 0 && num <= ${#options[@]} )) &&
      { printf "%s" "${options[$num-1]}"; break; } ||
      { msg="Invalid option: $num"; continue; }
    done
    IFS=${OLD_IFS}
  else
    echo 'optoins is none' >&2
    return 1
  fi
}

function mktmp() {
  local name subfix
  name=${1-tmp}
  subfix=$(echo ${2-.txt} | sed -E 's/^[^\.]/.&/')
  mktemp --tmpdir=$(pwd) -t "${name}.XXXXXX${subfix}"
}